package me.arvin.qa.jmeter.plugins.dependscontroller;

import java.util.HashMap;
import java.util.Map;

import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;

import org.apache.jmeter.gui.GuiPackage;
import org.apache.jmeter.gui.tree.JMeterTreeNode;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.NullProperty;

class DependsManageTreeLisener implements TreeModelListener {

	private static final DependsManageTreeLisener instance = new DependsManageTreeLisener();

	private static boolean addToTree = false;

	private DependsManageTreeLisener() {}

	static DependsManageTreeLisener getInstance() {
		return instance;
	}

	private static final Map<JMeterTreeNode, DependsRelationProperty> nodeRelationMap = new HashMap<>();

	public void addNodeDependsRelation(JMeterTreeNode node, DependsRelationProperty dc) {
		nodeRelationMap.put(node, dc);
	}

	public void removeNodeDependsRelation(JMeterTreeNode node) {
		nodeRelationMap.remove(node);
	}

	static void addToTree() {
		if (addToTree == false) {
			GuiPackage guiInstance = GuiPackage.getInstance();
			if (guiInstance != null) {
				guiInstance.getTreeModel().addTreeModelListener(DependsManageTreeLisener.getInstance());
			}
		}
	}

	@Override
	public void treeNodesChanged(TreeModelEvent e) {

		JMeterTreeNode node = (JMeterTreeNode) e.getChildren()[0];

		DependsRelationProperty drp = nodeRelationMap.get(node);
		if (drp != null) {
			TestElement te = ((TestElement) node.getUserObject());
			Object objectValue = te.getProperty(DependsController.DependsRelationList);

			if (objectValue instanceof NullProperty) {
				te.setProperty(drp);
			}
		}
	}

	@Override
	public void treeNodesInserted(TreeModelEvent e) {}

	@Override
	public void treeNodesRemoved(TreeModelEvent e) {
		removeNodeDependsRelation((JMeterTreeNode) e.getChildren()[0]);
	}

	@Override
	public void treeStructureChanged(TreeModelEvent e) {}

}